<?php
/**
 * Created by PhpStorm.
 * User: WX-C
 * Date: 2018/4/18
 * Time: 11:34
 */

namespace app\common\model;


use app\common\traits\Base;
use think\Db;
use think\Model;
use think\Request;

class Question extends Model
{
    use Base;
    protected $typeLang=[
        'checkbox'=>'多选',
        'radio'=>'单选',
        'textarea'=>'问答'
    ];
    protected function setExtAttr($value,$data){
        if($data['type']=='table'){
            $tmp=[
                'th'=>isset($data['th'])?$data['th']:$data['ext']['th'],
                'td'=>isset($data['td'])?$data['td']:$data['ext']['td']
            ];
        }else{
            $tmp=array_map(function($v,$m){
                return ['value'=>$v,'name'=>$m];
            },$data['feng'],$value);
        }
        return json_encode($tmp,JSON_UNESCAPED_UNICODE);
    }
    protected function getTypeShowAttr($value){
        return $this->typeLang[$value];
    }
    protected function getExtAttr($value){
        return empty($value)?[]:json_decode($value,true);
    }
    public function add($data){
        return $this->allowField(true)
            ->isUpdate(false)
            ->save($data);
    }
     function edit($data){
        return $this->allowField(true)
            ->isUpdate(true)
            ->save($data);
    }
    public function index(){
        $limit=input('limit',10,'intval');
        $page=input('page',1,'intval');
        $key=input('key/a',['name'=>'']);
        $where=array_filter(['name'=>['like',"%{$key['name']}%"]]);
        $lists=$this->field(['id','name','type','weight','ext'])
            ->page($page,$limit)
            ->where($where)
            ->select();
        $count=$this ->where($where)->count('id');
        return [$lists,$count];
    }

    public function idFind($id){
        return $lists=$this->find($id);
    }

    public function del($id){
        return $lists=$this->where(['id'=>['in',$id]])->delete();
    }
}